const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');

// 生成访问令牌
const generateAccessToken = (user) => {
  return jwt.sign(
    { username: user.username, id: user.id },
    process.env.JWT_SECRET,
    { expiresIn: process.env.JWT_EXPIRES_IN }
  );
};

// 生成刷新令牌
const generateRefreshToken = (user) => {
  return jwt.sign(
    { username: user.username, id: user.id },
    process.env.JWT_REFRESH_SECRET,
    { expiresIn: process.env.JWT_REFRESH_EXPIRES_IN }
  );
};

// 登录路由
router.post('/login', (req, res) => {
  const { username, password } = req.body;
  
  if (username === 'admin' && password === '123456') {
    const user = { username, id: 1 };
    const accessToken = generateAccessToken(user);
    const refreshToken = generateRefreshToken(user);

    res.json({
      success: true,
      message: '登录成功',
      data: {
        username,
        accessToken,
        refreshToken
      }
    });
  } else {
    res.status(401).json({
      success: false,
      message: '用户名或密码错误'
    });
  }
});

// 刷新token路由
router.post('/refresh-token', (req, res) => {
  const { refreshToken } = req.body;

  if (!refreshToken) {
    return res.status(401).json({
      success: false,
      message: '未提供刷新令牌'
    });
  }

  try {
    const user = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);
    const accessToken = generateAccessToken({ username: user.username, id: user.id });

    res.json({
      success: true,
      data: {
        accessToken
      }
    });
  } catch (err) {
    return res.status(401).json({
      success: false,
      message: '刷新令牌无效或已过期'
    });
  }
});

// 验证 token 的中间件
const verifyToken = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(403).json({
      success: false,
      message: '未提供token'
    });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({
      success: false,
      message: 'token无效或已过期'
    });
  }
};

// 获取用户信息的示例保护路由
router.get('/profile', verifyToken, (req, res) => {
  res.json({
    success: true,
    data: {
      username: req.user.username,
      id: req.user.id
    }
  });
});

// 注册路由
router.post('/register', (req, res) => {
  const { username, password } = req.body;
  
  // 这里是示例注册逻辑，实际项目中应该连接数据库存储用户信息
  res.json({
    success: true,
    message: '注册成功',
    data: { username }
  });
});

module.exports = router;